'use strict';

angular.module('myApp').controller('QuestionController', ['$scope', 'QuestionService', function($scope, QuestionService) {
    var self = this;
    self.question={id:null,title:'',content:'',createdTimestamp:'',lastModifiedTimestamp:''};
    self.questions=[];

    self.submit = submit;
    self.edit = edit;
    self.remove = remove;
    self.reset = reset;


    fetchAllQuestions();

    function fetchAllQuestions(){
        QuestionService.fetchAllQuestions()
            .then(
            function(d) {
                self.questions = d;
            },
            function(errResponse){
                console.error('Error while fetching Questions');
            }
        );
    }

    function createQuestion(question){
        QuestionService.createQuestion(question)
            .then(
            fetchAllQuestions,
            function(errResponse){
                console.error('Error while creating Question');
            }
        );
    }

    function updateQuestion(question, id){
        QuestionService.updateQuestion(question, id)
            .then(
            fetchAllQuestions,
            function(errResponse){
                console.error('Error while updating Question');
            }
        );
    }

    function deleteQuestion(id){
        QuestionService.deleteQuestion(id)
            .then(
            fetchAllQuestions,
            function(errResponse){
                console.error('Error while deleting Question');
            }
        );
    }

    function submit() {
        if(self.question.id===null){
            console.log('Saving New Question', self.question);
            createQuestion(self.question);
        }else{
            updateQuestion(self.question, self.question.id);
            console.log('Question updated with id ', self.question.id);
        }
        reset();
    }

    function edit(id){
        console.log('id to be edited', id);
        for(var i = 0; i < self.questions.length; i++){
            if(self.questions[i].id === id) {
                self.question = angular.copy(self.questions[i]);
                break;
            }
        }
    }

    function remove(id){
        console.log('id to be deleted', id);
        if(self.question.id === id) {//clean form if the question to be deleted is shown there.
            reset();
        }
        deleteQuestion(id);
    }


    function reset(){
        self.question={id:null,title:'',content:'',createdTimestamp:'',lastModifiedTimestamp:''};
        $scope.myForm.$setPristine(); //reset Form
    }

}]);
